package patrol.mobile.com.mobilepatrol.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGABanner;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.CygnActivity;
import patrol.mobile.com.mobilepatrol.activity.monitor.MonitorManagerHomeActivity;
import patrol.mobile.com.mobilepatrol.activity.office.OfficeHomeActivity;
import patrol.mobile.com.mobilepatrol.activity.rong.ConversationListActivity;
import patrol.mobile.com.mobilepatrol.activity.rong.SetTokenActivity;
import patrol.mobile.com.mobilepatrol.activity.security.SecurityManagerActivity;
import patrol.mobile.com.mobilepatrol.activity.toll.TollManagerHomeActivity;
import patrol.mobile.com.mobilepatrol.activity.yanghuke.YangHuActivity;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.CygnBean;
import patrol.mobile.com.mobilepatrol.bean.GridViewAddTitleBean;
import patrol.mobile.com.mobilepatrol.bean.MenuBean;
import patrol.mobile.com.mobilepatrol.bean.MenuConstants;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.view.OnGridViewAddTitleLisener;
import patrol.mobile.com.mobilepatrol.widget.GridViewAddTitleLayout;

/**
 * 新主页fragment.
 */
public class NewMainFragment extends BaseFragment {
    private List<MenuBean> menuBeanList;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.banner)
    BGABanner banner;
    @BindView(R.id.btn_first)
    Button btnFirst;
    @BindView(R.id.btn_second)
    Button btnSecond;
    @BindView(R.id.btn_third)
    Button btnThird;
    @BindView(R.id.topGridView)
    GridViewAddTitleLayout topGridView;
    @BindView(R.id.secondGridView)
    GridViewAddTitleLayout secondGridView;
    @BindView(R.id.callVideo)
    ImageView callVideo;
    @BindView(R.id.cygnRecyclerView)
    RecyclerView cygnRecyclerView;
    @BindView(R.id.cygnLayout)
    RelativeLayout cygnLayout;
    @BindView(R.id.tv_left_title)
    TextView tv_left_title;
    private String mParam1;
    private String mParam2;
//    private String[] tops = new String[]{"行政管理", "养护管理", "监控管理", "安保管理", "收费及服务"};
//    public String[] TITLES=this.getResources().getStringArray(R.array.security_activity_titles);
//    private int[] imgs = new int[]{R.mipmap.administrative_mana, R.mipmap.maintenance_mana, R.mipmap.monitoring_mana, R.mipmap.security_mana, R.mipmap.charge_mana};

    public NewMainFragment() {
    }

    /**
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewMainFragment.
     */
    public static NewMainFragment newInstance(String param1, String param2) {
        NewMainFragment fragment = new NewMainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_new_main;
    }

    @Override
    protected void initTitle() {
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("首页");
        callVideo.setVisibility(View.GONE);
        tv_left_title.setVisibility(View.GONE);
        tv_left_title.setText("聊天信息");
        tv_left_title.setTextSize(15);
        tv_left_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(ConversationListActivity.class);
            }
        });
        callVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SetTokenActivity.class);
            }
        });
    }

    @Override
    protected void initData() {
        topGridView.setTitleGone();
        secondGridView.setTitle("更多精彩");
        cygnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(CygnActivity.class);
            }
        });
        getHttpData();
    }


    /**
     * 获取机构
     */
    private void getHttpData() {
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("roleId", UserManager.getUserId());
        HttpSender sender = new HttpSender(getActivity(), baseUrl, Urls.getRoleMenuList);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser parser = new JsonParser();
                JsonObject asJsonObject = parser.parse(response).getAsJsonObject();
                JsonArray list = asJsonObject.getAsJsonArray("list");
                menuBeanList=GsonUtil.jsonToList(list.toString(),MenuBean.class);
                topGridView.setGridViewAddTitleBeans(getFirstData(1),menuBeanList);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        getCyxxData();
    }

    //获取常用信息
    List<CygnBean> selectBeans;

    private void getCyxxData() {
        String CYXX = (String) SPUtils.get(UserManager.getUserId() + SPUtils.CYXXDATA, "");
        if (TextUtils.isEmpty(CYXX)) {
            selectBeans = new ArrayList<>();
        } else {
            selectBeans = GsonUtil.jsonToList(CYXX, CygnBean.class);
        }
        cygnRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        SelectContentAdapter selectContentAdapter = new SelectContentAdapter();
        cygnRecyclerView.setAdapter(selectContentAdapter);
    }

    /**
     * 设置第一块数据
     */
    private List<GridViewAddTitleBean> getFirstData(int what) {
        List<GridViewAddTitleBean> list = new ArrayList<>();
//        String[] title;
//        int[] imgs;
//        title = MenuConstants.HOME_CHILD_TITLES_1;
//        imgs=MenuConstants.HOME_CHILD_IMGS_1;
        for (int i = 0; i < MenuConstants.HOME_CHILD_TITLES_1.length; i++) {
            GridViewAddTitleBean gridViewAddTitleBean = new GridViewAddTitleBean();
            gridViewAddTitleBean.setTitle(MenuConstants.HOME_CHILD_TITLES_1[i]);
            gridViewAddTitleBean.setImage(MenuConstants.HOME_CHILD_IMGS_1[i]);
            list.add(gridViewAddTitleBean);
        }
        return list;
    }

    @Override
    protected void initListener() {
//        Intent intent=new Intent();
        Bundle bundle=new Bundle();
        topGridView.setOnItemClickListener(new OnGridViewAddTitleLisener() {
            @Override
            public void onLisener(View view, int position) {
                switch (position) {
                    case 0:
                        bundle.putSerializable(MenuConstants.MENU_DATA, (Serializable) menuBeanList);
                        startActivity(bundle,OfficeHomeActivity.class);//办公室
                        CommonUtil.openNewActivityAnim(getActivity(), false);
                        break;
                    case 1:
                        bundle.putSerializable(MenuConstants.MENU_DATA, (Serializable) menuBeanList);
                        startActivity(bundle,YangHuActivity.class);
//                        startActivity(YangHuActivity.class);//养护科
                        CommonUtil.openNewActivityAnim(getActivity(), false);
                        break;
                    case 2:
                        bundle.putSerializable(MenuConstants.MENU_DATA, (Serializable) menuBeanList);

                        startActivity(bundle,MonitorManagerHomeActivity.class);//监控管理
                        CommonUtil.openNewActivityAnim(getActivity(), false);
                        break;
                    case 3:
                        bundle.putSerializable(MenuConstants.MENU_DATA, (Serializable) menuBeanList);

                        //startActivity(SecurityManagerHomeActivity.class);//安保管理 原安保管理界面
                        startActivity(bundle,SecurityManagerActivity.class);//安保管理
                        CommonUtil.openNewActivityAnim(getActivity(), false);
                        break;
                    case 4:
                        bundle.putSerializable(MenuConstants.MENU_DATA, (Serializable) menuBeanList);

                        startActivity(bundle,TollManagerHomeActivity.class);//收费稽查以及服务区管理
                        CommonUtil.openNewActivityAnim(getActivity(), false);
                        break;
                }
            }
        });
        //这个接口不暴露会导致崩溃
        secondGridView.setOnTitleLayoutClickListener(new GridViewAddTitleLayout.OnTitleLayoutClickListener() {
            @Override
            public void onClick() {

            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public class SelectContentAdapter extends RecyclerView.Adapter<SelectContentAdapter.ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_content_layout, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.itemTet.setText(selectBeans.get(position).getTitle());
            holder.itemImage.setImageResource(selectBeans.get(position).getIcon());
            holder.itemImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectBeans.get(position).getTarget() != null) {
                        Intent intent = new Intent();
                        intent.setClassName(getActivity(), selectBeans.get(position).getTarget());
                        intent.putExtra("TITLE_STRING", selectBeans.get(position).getTitle());
                        getActivity().startActivity(intent);
                    }
//                    selectBeans.get(position).getIntdex()
                }
            });
        }

        @Override
        public int getItemCount() {
            return selectBeans == null ? 0 : selectBeans.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.itemImage)
            ImageView itemImage;
            @BindView(R.id.itemTet)
            TextView itemTet;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }


    private void connect(String token) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                showToast("Token错误");
            }

            @Override
            public void onSuccess(String userid) {
                showToast("Token成功");
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                showToast("连接融云失败");
            }
        });
    }
}
